import os
from typing import List

from fastapi import UploadFile
from fastapi.routing import APIRouter
from starlette.responses import StreamingResponse

from settings import get_root_path

img_router = APIRouter(prefix="/img", tags=["图片访问"])


@img_router.post("/uploadfile")
async def upload_file(file: UploadFile | None = None):
    """
        上传文件,参数file可选，如果是必传，可以直接声明为 (file: UploadFile) 格式
    :param file:
    :return:
    """
    print("file size: %d, content_type: %s" % (file.size, file.content_type))
    return {"file_name": file.filename}


@img_router.post("/uploadfiles")
async def upload_file(files: List[UploadFile]):
    """
        多上传文件,参数files 必传，参考: https://fastapi.tiangolo.com/zh/tutorial/request-files/
    :param files: 多文件
    :return:
    """
    for file in files:
        print("file name: %s, size: %d, content_type: %s" % (file.filename, file.size, file.content_type))
    return {"file_size": len(files)}


@img_router.get("/pic/{file}")
async def pic_preview(file: str):
    """
    返回图片/流内容
    :param file:
    :return:
    """
    root_path = get_root_path()
    return StreamingResponse(open(os.path.join(root_path, "static", file), 'rb'),
                             media_type="image/png")
